package com.ryan.ohos.extension.widget.viewpager;

import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.ability.fraction.FractionManager;
import ohos.aafwk.ability.fraction.FractionScheduler;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;

import java.util.Optional;

public abstract class FractionPagerAdapter extends PagerAdapter {
    private static final String TAG = "FragmentPagerAdapter";
    private static final boolean DEBUG = false;

    private final FractionManager mFragmentManager;
    private FractionScheduler mCurTransaction = null;
    private Fraction mCurrentPrimaryItem = null;

    /**
     * Constructor for {@link FractionPagerAdapter}.
     *
     * @param fm fragment manager that will interact with this adapter
     */
    public FractionPagerAdapter(FractionManager fm) {
        mFragmentManager = fm;
    }

    /**
     * Return the Fragment associated with a specified position.
     */
    public abstract Fraction getItem(int position);

    @Override
    public void startUpdate(ComponentContainer container) {
        if (container.getId() == -1) {
            throw new IllegalStateException("ViewPager with adapter " + this
                    + " requires a view id");
        }
    }

    @Override
    public Object instantiateItem(ComponentContainer container, int position) {
        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.startFractionScheduler();
        }

        final long itemId = getItemId(position);

        // Do we already have this fragment?
        String name = makeFragmentName(container.getId(), itemId);
//        Optional<Fraction> op = mFragmentManager.getFractionByTag(name);
        Fraction fragment;
//        if (op.isPresent()) {
//            fragment = op.get();
//            mCurTransaction.replace(container.getId(), fragment); // FractionScheduler的replace函数有bug，横屏切换后导致fraction无法显示，暂时去掉
//        } else {
            fragment = getItem(position);
            mCurTransaction.add(container.getId(), fragment,
                    makeFragmentName(container.getId(), itemId));
//        }
//        if (fragment != mCurrentPrimaryItem) {
//            fragment.setMenuVisibility(false);
//            if (mBehavior == BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
//                mCurTransaction.setMaxLifecycle(fragment, Lifecycle.State.STARTED);
//            } else {
//                fragment.setUserVisibleHint(false);
//            }
//        }

        return fragment;
    }

    @Override
    public void destroyItem(ComponentContainer container, int position, Object object) {
        Fraction fragment = (Fraction) object;

        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.startFractionScheduler();
        }
//        if (DEBUG) Log.v(TAG, "Detaching item #" + getItemId(position) + ": f=" + object
//                + " v=" + (fragment.getView()));
        mCurTransaction.remove(fragment);
        if (fragment == mCurrentPrimaryItem) {
            mCurrentPrimaryItem = null;
        }
    }

    @Override
    public void setPrimaryItem(ComponentContainer container, int position, Object object) {
//        Fraction fragment = (Fraction)object;
//        if (fragment != mCurrentPrimaryItem) {
//            if (mCurrentPrimaryItem != null) {
//                mCurrentPrimaryItem.setMenuVisibility(false);
//                if (mBehavior == BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
//                    if (mCurTransaction == null) {
//                        mCurTransaction = mFragmentManager.startFractionScheduler();
//                    }
//                    mCurTransaction.setMaxLifecycle(mCurrentPrimaryItem, Lifecycle.State.STARTED);
//                } else {
//                    mCurrentPrimaryItem.setUserVisibleHint(false);
//                }
//            }
//            fragment.setMenuVisibility(true);
//            if (mBehavior == BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
//                if (mCurTransaction == null) {
//                    mCurTransaction = mFragmentManager.beginTransaction();
//                }
//                mCurTransaction.setMaxLifecycle(fragment, Lifecycle.State.RESUMED);
//            } else {
//                fragment.setUserVisibleHint(true);
//            }
//
//            mCurrentPrimaryItem = fragment;
//        }
    }

    @Override
    public void finishUpdate(ComponentContainer container) {
        if (mCurTransaction != null) {
            mCurTransaction.submit();
            mCurTransaction = null;
        }
    }

    @Override
    public boolean isViewFromObject(Component view, Object object) {
        return ((Fraction)object).getComponent() == view;
    }

    /**
     * Return a unique identifier for the item at the given position.
     *
     * <p>The default implementation returns the given position.
     * Subclasses should override this method if the positions of items can change.</p>
     *
     * @param position Position within this adapter
     * @return Unique identifier for the item at position
     */
    public long getItemId(int position) {
        return position;
    }

    private static String makeFragmentName(int viewId, long id) {
        return "ohos:switcher:" + viewId + ":" + id;
    }
}
